<template>
  <div class="max-w-4xl mx-auto p-4">
    <!-- 聊天记录 -->
    <div class="bg-white rounded-xl shadow-lg p-6 mb-6 h-[70vh] min-h-[500px] overflow-y-auto">
      <div v-for="(msg, index) in messages" :key="index" class="mb-6 last:mb-0">
        <!-- 用户消息靠右 -->
        <div :class="msg.role === 'user' ? 'flex justify-end' : 'flex justify-start'">
          <div
            :class="[
              'p-4 rounded-2xl max-w-[85%]',
              msg.role === 'user'
                ? 'bg-blue-600 text-white'
                : 'bg-blue-50 text-gray-800'
            ]"
          >
            <!-- 用户消息 -->
            <template v-if="msg.role === 'user'">
              <div class="text-lg font-medium leading-relaxed">
                {{ msg.content }}
              </div>
              <!-- 只在消息中显示一次附件标识 -->
              <div v-if="msg.attachment" class="text-sm mt-2 opacity-80">
                📎 {{ msg.attachment.name }}
              </div>
            </template>

            <!-- AI 消息 -->
            <template v-else>
              <div 
                class="markdown-body prose prose-lg max-w-none text-gray-700"
                v-html="renderMarkdown(msg.content)"
              ></div>
            </template>
          </div>
        </div>
      </div>
    </div>

    <!-- 文件上传预览 -->
    <div v-if="currentFile" class="flex items-center bg-blue-100 rounded-lg p-3 mb-4">
      <span class="flex-1 text-blue-800 font-medium">📄 {{ currentFile.name }}</span>
      <button @click="removeFile" class="text-blue-600 hover:text-blue-800 transition-colors">
        <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
        </svg>
      </button>
    </div>

    <!-- 控制区域 -->
    <div class="space-y-4">
      <!-- 输入区域 -->
      <div class="flex gap-3">
        <div class="flex-1 flex gap-3">
          <input
            v-model="userInput"
            type="text"
            placeholder="输入消息..."
            class="flex-1 px-5 py-3 text-lg border-2 border-gray-200 rounded-xl focus:ring-4 focus:ring-blue-200 focus:border-blue-500 outline-none transition-all"
            @keyup.enter="sendMessage"
          />
          <label class="cursor-pointer bg-white border-2 border-gray-200 p-3 rounded-xl hover:bg-gray-50 relative group">
            <span class="text-2xl">📎</span>
            <input
              type="file"
              class="hidden"
              accept=".doc,.docx"
              @change="handleFileUpload"
            />
            <div class="absolute bottom-full mb-2 bg-gray-800 text-white text-xs px-3 py-1 rounded-lg hidden group-hover:block">
              支持 Word 文档
            </div>
          </label>
        </div>
        <button
          @click="sendMessage"
          class="px-6 py-3 bg-blue-600 hover:bg-blue-700 text-white font-medium text-lg rounded-xl transition-colors disabled:bg-gray-400 flex items-center justify-center"
          :disabled="isLoading"
        >
          <template v-if="isLoading">
            <svg class="animate-spin -ml-1 mr-2 h-6 w-6 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
              <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
              <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
            </svg>
            发送中
          </template>
          <template v-else>
            发送
          </template>
        </button>
      </div>

      <!-- 模型选择器 -->
      <div class="flex items-center gap-3">
        <label class="text-sm font-medium text-gray-600">模型选择：</label>
        <select
          v-model="selectedModel"
          class="bg-white border-2 border-gray-200 rounded-lg px-4 py-2 text-base focus:ring-4 focus:ring-blue-200 focus:border-blue-500 outline-none transition-all"
        >
          <option 
            v-for="model in AVAILABLE_MODELS" 
            :key="model.value" 
            :value="model.value"
            class="text-gray-700"
          >
            {{ model.label }}
          </option>
        </select>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { chatWithAI } from '~/services/ai'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'

// 配置 marked
marked.setOptions({
  highlight: function(code: string, language: string) {
    const lang = hljs.getLanguage(language) ? language : 'plaintext';
    return hljs.highlight(code, { language: lang }).value;
  } as marked.Highlighter,
  langPrefix: 'hljs language-',
  gfm: true,
  breaks: true
});

interface Message {
  role: 'user' | 'assistant' | 'system';
  content: string;
  attachment?: {
    name: string;
    content: string;
  };
}

const AVAILABLE_MODELS = [
  { value: 'deepseek-ai/DeepSeek-R1', label: 'DeepSeek-R1' },
  { value: 'deepseek-ai/DeepSeek-V3', label: 'DeepSeek-V3' },
  { value: 'Qwen/Qwen2.5-72B-Instruct-128K', label: 'Qwen2.5-72B' }
]

const messages = ref<Message[]>([])
const userInput = ref('')
const isLoading = ref(false)
const selectedModel = ref(AVAILABLE_MODELS[0].value)
const currentFile = ref<File | null>(null)
const currentFileContent = ref<string>('')

async function handleFileUpload(event: Event) {
  const input = event.target as HTMLInputElement
  if (input.files && input.files[0]) {
    const file = input.files[0]
    currentFile.value = file

    const formData = new FormData()
    formData.append('file', file)

    try {
      const response = await fetch('/api/upload', {
        method: 'POST',
        body: formData
      })

      if (!response.ok) {
        throw new Error('Upload failed')
      }

      const result = await response.json()
      currentFileContent.value = result.text
    } catch (error) {
      console.error('Upload error:', error)
      alert('文件上传失败')
      removeFile()
    }
  }
}

function removeFile() {
  currentFile.value = null
  currentFileContent.value = ''
}

async function sendMessage() {
  if ((!userInput.value.trim() && !currentFileContent.value) || isLoading.value) return

  // 构建显示用消息（不包含附件内容）
  let displayMessage = userInput.value;
  // if (currentFile.value) {
  //   displayMessage += `\n\n📎 附件: ${currentFile.value.name}`;
  // }

  // 添加到消息历史（只显示文件名）
  messages.value.push({
    role: 'user',
    content: displayMessage,
    attachment: currentFile.value ? {
      name: currentFile.value.name,
      content: currentFileContent.value
    } : undefined
  });

  // 构建包含完整内容的发送数据
  const messagesToSend = messages.value.map(msg => {
    if (msg.role === 'user' && msg.attachment) {
      return {
        ...msg,
        content: `${msg.content}\n\n附件内容:\n${msg.attachment.content}`
      }
    }
    return msg
  });

  userInput.value = ''
  isLoading.value = true

  try {
    const response = await chatWithAI(
      messagesToSend,
      selectedModel.value
    )

    messages.value.push({
      role: 'assistant',
      content: response
    })
  } catch (error) {
    console.error('Error:', error)
    messages.value.push({
      role: 'assistant',
      content: '抱歉，发生了一些错误，请稍后再试。'
    })
  } finally {
    isLoading.value = false
    removeFile()
  }
}

function renderMarkdown(content: string): string {
  try {
    return marked(content)
  } catch (e) {
    console.error('Markdown parsing error:', e)
    return content
  }
}
</script>

<style>
.markdown-body {
  @apply text-lg leading-relaxed;
}

.markdown-body pre {
  @apply p-4 rounded-xl bg-gray-800 text-gray-100;
}

.markdown-body code {
  @apply px-2 py-1 bg-gray-100 rounded-lg text-base;
}

.markdown-body table {
  @apply rounded-lg overflow-hidden shadow-sm;
}

.markdown-body blockquote {
  @apply px-4 py-2 bg-blue-50 border-l-4 border-blue-500 italic text-gray-700;
}
</style> 